import Promise from 'bluebird';
import { ajax } from 'm7-ajax';
import { APIORIGIN } from './meta';

const APIOrigin = `${APIORIGIN}appservice`;

function request ({ origin, path, query = '' }) {
  const whole = query.length <= 0 ? `${origin}/${path}` : `${origin}/${path}?${query}`;
  return new Promise((resolve, reject) => {
    ajax({
      url: `${whole}`,
      onSuccess (data) {
        resolve(data);
      },
      onError (error) {
        reject(error);
      }
    });
  });
}

function requestParams () {
  const search = window.location.search;
  const searchToObject = stringToObject(search.slice(1));
  if (search && searchToObject.code) {
    return {
      status: 1,
      origin: APIOrigin,
      code: searchToObject.code
    };
  }
}

function stringToObject (str) {
  return str.split('&').reduce((result, currentValue) => {
    const currentValueList = currentValue.split('=');
    result[currentValueList[0]] = currentValueList[1];
    return result;
  }, {});
}
function dealScore (score) {
  if (score) {
    return Math.round(score);
  }
  return 0;
}
function dealNumber (n) {
  if (n > 10000) {
    return (n / 10000).toFixed(2) + '万';
  }
  return n;
}
function formatDate (now) {
  const year = now.getYear() + 1900;
  let month = now.getMonth() + 1;
  let date = now.getDate();
  let hour = now.getHours();
  let minute = now.getMinutes();
  month = month.toString().length > 1 ? month : `0${month}`;
  date = date.toString().length > 1 ? date : `0${date}`;
  hour = hour.toString().length > 1 ? hour : `0${hour}`;
  minute = minute.toString().length > 1 ? minute : `0${minute}`;
  return year + '.' + month + '.' + date + ' ' + hour + ':' + minute;
}

function formatSecond (duration = 0) {
  let hour, minute;
  minute = Math.floor(duration / 60);
  const second = duration % 60;
  if (minute >= 60) {
    hour = Math.floor(minute / 60);
    minute = minute % 60;
    return `${hour}时${minute}分${second}秒`;
  }
  return minute <= 0 ? `${second}秒` : `${minute}分${second}秒`;
}

function formatZoomPic (src) {
  const hash = new Date().getTime();
  if (/\/zoom\//.test(src)) {
    const startSite = src.indexOf('zoom');
    const picSize = src.slice(startSite + 5).split('/');
    if (picSize[0] > 1080) {
      const cell = Math.ceil(picSize[0] / 680);
      return `${src.slice(0, startSite + 5)}${Math.floor(picSize[0] / cell)}/${Math.floor(picSize[1] / cell)}?${hash}`;
    }
    return `${src.slice(0, startSite)}?${hash}`;
  }
  return src;
}

export default {
  request,
  requestParams,
  dealScore,
  dealNumber,
  formatDate,
  formatSecond,
  formatZoomPic
};
